package org.ruiyichen.guizhou.agr.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;

import org.ruiyichen.guizhou.agr.R;
import org.ruiyichen.guizhou.agr.base.BaseFragment;
import org.ruiyichen.guizhou.agr.base.DataManger;
import org.ruiyichen.guizhou.agr.bean.Response;
import org.ruiyichen.guizhou.agr.bean.mode.IIrrigatedAreaModel;
import org.ruiyichen.guizhou.agr.config.Constant;
import org.ruiyichen.guizhou.agr.imp.IIrrigatedAreaFilter;
import org.ruiyichen.guizhou.agr.net.OkHttpManager;
import org.ruiyichen.guizhou.agr.ui.activity.AddIrrigatedAreaActivity;
import org.ruiyichen.guizhou.agr.ui.activity.DefaultDeviceActivity;
import org.ruiyichen.guizhou.agr.ui.activity.HomeActivity;
import org.ruiyichen.guizhou.agr.ui.activity.IrrigatedAreaManageActivity;
import org.ruiyichen.guizhou.agr.ui.activity.IrrigatedDeviceControlActivity;
import org.ruiyichen.guizhou.agr.ui.adapter.IrrigatedAreaRecyclerAdapter;
import org.ruiyichen.guizhou.agr.ui.listener.OnRecyclerItemClick;
import org.ruiyichen.guizhou.agr.ui.mineview.BToast;
import org.ruiyichen.guizhou.agr.utils.ListUtil;
import org.ruiyichen.guizhou.agr.utils.StrUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 控制
 */
public class ControlFragment extends BaseFragment implements View.OnClickListener {

    private boolean canNext = false;


    private RecyclerView rv_nf_info_root;


    //-------------------------------
    TextView
            tv_normal_other;

    private IrrigatedAreaRecyclerAdapter adapter;

    private List<IIrrigatedAreaModel> list = new ArrayList<>();

    private boolean isEdit = true;

    @Override
    public void onResume() {
        super.onResume();
        if (!getUserVisibleHint()) {
            return;
        }
        initData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            bHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    initData();
                }
            }, 500);
        }
        super.onHiddenChanged(hidden);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mRootView == null) {
            mRootView = inflater.inflate(R.layout.df_fragment_nav_control, container, false);
            bOkHttpManager = new OkHttpManager(getActivity(), bHandler);
            initViews();
            initEvents();
            initData();
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) mRootView.getParent();
        if (parent != null) {
            parent.removeView(mRootView);
        }
        return mRootView;
    }

    private void initViews() {
        setTitle("灌区").setRightImage(R.drawable.df_image_edit).setRightText(null);
        rv_nf_info_root = mRootView.findViewById(R.id.rv_home_control);
        LinearLayoutManager manager = new LinearLayoutManager(getCustomActivity());
        manager.setAutoMeasureEnabled(true);
        rv_nf_info_root.setLayoutManager(manager);
        rv_nf_info_root.setNestedScrollingEnabled(false);

        list.add(new IIrrigatedAreaModel(false, "默认区域（0个设备）", false));
        list.add(new IIrrigatedAreaModel(false, "东边1#灌区（2个设备）", true));

        adapter = new IrrigatedAreaRecyclerAdapter(getCustomActivity());
        adapter.setmDatas(list);
        rv_nf_info_root.setAdapter(adapter);

        tv_normal_other = mRootView.findViewById(R.id.tv_normal_other);
        setOtherMenu(isEdit);
    }

    private void setOtherMenu(boolean isEdit) {
        if (isEdit) {
            tv_normal_other.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.df_image_edit, 0);
            tv_normal_other.setText(null);
        } else {
            tv_normal_other.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            tv_normal_other.setText("编辑");
        }
    }


    private void initEvents() {
        tv_normal_other.setOnClickListener(this);
        adapter.setOnRecyclerItemClick(new OnRecyclerItemClick() {
            @Override
            public void onItemClick(View view, int position) {
                if (list.get(position).hasIDevice()) {
                    //灌区设备控制
                    Intent it = new Intent(getCustomActivity(), IrrigatedDeviceControlActivity.class);
                    it.putExtra(IrrigatedDeviceControlActivity.PAGE_TITLE, list.get(position).getIIrrigatedAreaDesc());
                    it.putExtra(IrrigatedDeviceControlActivity.TAG_ID, list.get(position).irrigId);
                    it.putExtra(Constant.ParamKey.IRRIGATED_AREA, list.get(position));
                    getCustomActivity().startActivity(it);
                    return;
                }
                //默认设备
                Intent it = new Intent(getCustomActivity(), DefaultDeviceActivity.class);
                it.putExtra(DefaultDeviceActivity.TAG_ID, list.get(position).irrigId);
                getCustomActivity().startActivity(it);
            }
        });
    }

    @Override
    public boolean onBackPressed() {
        return false;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_normal_other:
                //灌区管理
                Intent it = new Intent(getCustomActivity(), IrrigatedAreaManageActivity.class);
                startActivity(it);
                break;
        }
    }

    private HomeActivity getCustomActivity() {
        return (HomeActivity) getActivity();
    }

    private void initData() {
        //http://localhost/dev-api/asset/irrig/list?pageNum=1&pageSize=10
        Map<String, String> body = new HashMap<>();
        body.put("pageNum", "1");
        body.put("pageSize", "10");
        bOkHttpManager.httpRequest(Constant.RequestType.GET_IRRIGATED_LIST, Constant.Http.GET, body, false, new
                TypeToken<Response<Void, ArrayList<IIrrigatedAreaModel>>>() {
                }.getType(), true, false);
    }

    @Override
    protected void onPostHandle(int requestType, Object response, boolean error, int errorCode, Object obj1, Object obj2) {
        super.onPostHandle(requestType, response, error, errorCode, obj1, obj2);
        if (error) {
            BToast.getInstance().show(getResources().getString(R.string.abnormal));
        } else {
            if (response == null) {
                BToast.getInstance().show(getResources().getString(R.string.datafailure));
            } else {
                if (requestType == Constant.RequestType.GET_IRRIGATED_LIST) {
                    Response<Void, List<IIrrigatedAreaModel>> result = (Response<Void, List<IIrrigatedAreaModel>>) response;
                    if (result.isSuccess()) {
                        list.clear();
                        if (ListUtil.isNotEmpty(result.getRows())) {
                            list.addAll(result.getRows());
                        }
                        adapter.notifyDataSetChanged();
                    } else {
                        BToast.getInstance().show(result.getMsg());
                    }
                }
            }
        }
    }
}

